<template>
  <KiFormDialog
    :show.sync="dialogVisible"
    v-model="form"
    title="发货"
    :loading="inRequest"
    :submit="confirm"
  >
    <orderInfo v-if="!isEdit" v-model="info" />
    <template #el-form>
      <el-form-item label="物流形式" required>
        <el-select v-model="mode" filterable>
          <el-option label="物流配送" :value="0"></el-option>
          <el-option label="无需物流" :value="1"></el-option>
          <el-option label="上门自提" :value="2"></el-option>
          <el-option label="同城跑腿" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <template v-if="mode == 0">
        <el-form-item label="物流公司" required prop="logisticsCompany" verify>
          <el-select v-model="form.logisticsCompany" filterable>
            <el-option
              v-for="(item, i) in logisticsCompanyOpt"
              :key="i"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" required prop="logisticsNum" verify>
          <el-input
            v-model.trim="form.logisticsNum"
            placeholder="请输入物流单号"
          ></el-input>
        </el-form-item>
      </template>
    </template>
  </KiFormDialog>
</template>
<script>
import API from './api'
import orderInfo from './_orderInfo'
export default {
  components: {
    orderInfo
  },
  data () {
    return {
      dialogVisible: false,
      orderId: '',
      inRequest: false,
      form: {},
      logisticsCompanyOpt: [],
      info: null,
      mode: 0, //物流形式
      isEdit: false
    }
  },
  methods: {
    open (orderId) {
      //发货
      this.isEdit = false
      this.form = {} //打开另外一条数据, 需清掉form
      this.orderId = orderId
      this.init()
    },
    edit (orderId) {
      //编辑发货
      this.isEdit = true
      this.form = {}
      this.orderId = orderId
      this.init()
    },
    init () {
      //打开弹窗,准备数据
      this.dialogVisible = true

      API.expressCompany().then(({ data }) => {
        // console.log('所有快递公司', data);
        this.logisticsCompanyOpt = data
      })

      API.getOrderInfo({
        orderId: this.orderId
      }).then(({ data }) => {
        this.info = data
      })
    },
    confirm () {
      //提交发货

      // 因后端接口没做mode类型处理, 非物流信息状态时, 前端清空一下单号和物流公司字段.
      if (this.mode !== 0) {
        this.form.logisticsCompany = ''
        this.form.logisticsNum = ''
      }

      // 提交发货信息到服务器
      this.inRequest = true
      const api = this.isEdit ? API.modifyDeliver : API.deliver
      api({
        orderId: this.orderId,
        type: this.mode,
        ...this.form
      })
        .then(({ data }) => {
          this.$swal.success('操作成功')
          this.$emit('save')
          this.dialogVisible = false
        })
        .finally(() => {
          this.inRequest = false
        })
    }
  }
}
</script>
